package com.dz.lm.service.useragent.impl;

import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.dz.lm.common.dto.PageDto;
import com.dz.lm.common.dto.UserAgentDTO;
import com.dz.lm.common.dto.UserProductDTO;
import com.dz.lm.common.exception.DaoException;
import com.dz.lm.common.exception.ServiceException;
import com.dz.lm.common.util.JPushUtils;
import com.dz.lm.common.util.StringUtil;
import com.dz.lm.common.utils.DateUtil;
import com.dz.lm.dao.appLogin.read.AppLoginDao;
import com.dz.lm.dao.useragent.write.UserAgentDao;
import com.dz.lm.dao.userproduct.write.UserProductDao;
import com.dz.lm.domain.agentreview.AgentReview;
import com.dz.lm.domain.useragent.UserAgent;
import com.dz.lm.domain.useragent.UserAgentExample;
import com.dz.lm.domain.usermessage.UserMessage;
import com.dz.lm.domain.userproduct.UserProduct;
import com.dz.lm.domain.userproduct.UserProductExample;
import com.dz.lm.service.agentreview.AgentReviewService;
import com.dz.lm.service.product.ProductService;
import com.dz.lm.service.useragent.UserAgentService;
import com.dz.lm.service.userapply.UserApplyService;
import com.dz.lm.service.userapply.impl.UserApplyServiceImpl;
import com.dz.lm.service.usermessage.UserMessageService;
import com.dz.lm.service.userproduct.UserProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import org.apache.commons.lang.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.management.resources.agent;

import javax.annotation.Resource;
import javax.sound.sampled.Line;
import java.text.ParseException;
import java.util.*;

/**
 * @version 1.8;
 * @author: LDY;
 * @Description;
 * @Date: Created in 2020/3/7 20:54;
 */
@Service("userAgentService")
public class UserAgentServiceImpl implements UserAgentService {
    @Autowired
    private UserProductService userProductService;
    @Resource(name = "writeUserAgentDao")
    private UserAgentDao writeUserAgentDao;
    @Resource(name = "readUserAgentDao")
    private com.dz.lm.dao.useragent.read.UserAgentDao readUserAgentDao;
    @Resource(name = "readAppLoginDao")
    private AppLoginDao rAppLoginDao;
    @Resource(name = "writeUserProductDao")
    private UserProductDao writeUserProductDao;
    @Autowired
    private UserApplyService userApplyService;
    @Resource(name = "readUserProductDao")
    private com.dz.lm.dao.userproduct.read.UserProductDao readUserProductDao;
    @Resource(name = "readLoginLogDao")
    private com.dz.lm.dao.log.read.LoginLogDao loginLogDao;
    public Logger logger = LogManager.getLogger(getClass());
    @Autowired
    private AgentReviewService agentReviewService;
    @Autowired
    private UserMessageService userMessageService;
    @Override
    @Transactional
    public Map add(int userId, int productId, boolean isLunch, String platform, boolean isReview, String template, String urls ,double returnPoint , double agentSale ,String levelNum) throws ServiceException {
        Map map = new HashMap();
        int ret = 0;
        UserProductExample pex = new UserProductExample();
        pex.setOrderByClause("update_time desc");
        UserProductExample.Criteria pcr = pex.createCriteria();
        pcr.andUserIdEqualTo(userId);
        UserProductDTO detail = userProductService.getDetail(0, productId, false);
        if(detail.getCompPid() > 0){
            pex.setCompPid(detail.getCompPid());
        }else {
            pcr.andSuperIdEqualTo(productId);
            pcr.andProductTypeEqualTo(2);
        }
        if (detail == null) {
            ret = -996; //产品已删除
            map.put("ret",ret);

            return map;
        }
        try {
            if(isReview && detail.getIsReview() == 1){ //判断代理审核是否未处理。未处理不能代理
                int i = agentReviewService.queryCount(0, userId, productId, 0);
                if(i >0){
                    ret = -995;
                    map.put("ret",ret);

                    return map;
                }
            }
            List<UserProduct> list = readUserProductDao.selectByExample(pex);
            if (list != null && list.size() > 0) { //已经代理过的代理不可再申请
                UserProduct preProduct = list.get(0);
                if ((preProduct.getAgentStatus() == 1 || preProduct.getAgentStatus() == 4 || preProduct.getCompPid() > 0) && preProduct.getStatus() != 3) { //正常代理，和返点发生变化时，不可再次代理
                    ret = -997;
                    map.put("ret",ret);
                    return map;
                }
                if (preProduct.getAgentStatus() == 2 || preProduct.getAgentStatus() == 3) {//代理状态为 2产品下架,删除3-取消代理，时判断时间是否大于三十天
                    Date time = DateUtil.getDateTimeByDay(preProduct.getUpdateTime());
                    Calendar instance = Calendar.getInstance();
                    instance.setTime(time);
                    instance.add(Calendar.DAY_OF_MONTH, 30);
                    Date time1 = instance.getTime();
                    int i = time1.compareTo(new Date());
                    if (time1.compareTo(new Date()) > 0) {
                        ret = -998;
                        map.put("ret",ret);

                        return map;
                    }
                }

             /*  switch (preProduct .getStatus()){
                   case 1: //未发布
                   case 2: //发布
                       if(preProduct.getAgentStatus() == 1 || preProduct.getAgentStatus() ==4){ //正常代理，和返点发生变化时，不可再次代理
                           return -997;
                       }else {//代理状态为 2产品下架,删除3-取消代理，时判断时间是否大于三十天
                           Date time = DateUtil.getDateTimeByDay(preProduct.getUpdateTime());
                           Calendar instance = Calendar.getInstance();
                           instance.setTime(time);
                           instance.add(Calendar.DAY_OF_MONTH, 30);
                           Date time1 = instance.getTime();
                           if (time1.compareTo(new Date()) > 0) {

                           } else {
                               return -998;
                           }
                       }
                       break;
                   case 3:
                       if(preProduct.getAgentStatus() ==2 || preProduct.getAgentStatus() ==3)
                       break;
               }*/
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }

        UserProduct userProduct = new UserProduct();
        BeanUtils.copyProperties(detail, userProduct);
        userProduct.setProductId(0);
        userProduct.setSuperId(productId);
        if (isLunch) {
            userProduct.setStatus(2);//发布
        } else {
            userProduct.setStatus(1);//未发布
        }
        userProduct.setProductType(2);//代理产品
        userProduct.setAgentStatus(1);//正常代理
        userProduct.setUserId(userId);
    if(!StringUtil.containEmpty(levelNum)){
        userProduct.setLevelNum(levelNum);//代理级别
    }
        userProduct.setRank(0);//代理排名
        if(agentSale > 0){
            userProduct.setAgentSale(agentSale);
        }
        if(returnPoint > 0){
            userProduct.setReturnPoint(returnPoint);
        }
        userProduct.setCreateTime(DateUtil.getTimeStr(new Date()));
        int add = userProductService.add(userProduct);
        //处理代理信息
        if (add > 0) {
            if(!StringUtil.containEmpty(detail.getAgentMessage()) && detail.getIsReview() ==0){
                UserMessage message = new UserMessage();
                message.setUserId(userId);
                message.setSendUid(detail.getSource());
                message.setMessage(detail.getProductName()+"的代理推送:  "+detail.getAgentMessage());
                message.setCreateTime(DateUtil.getTimeStr(new Date()));
                userMessageService.add(message);
            }
            ret = 1;
            UserAgentExample ex = new UserAgentExample();
            UserAgentExample.Criteria cr = ex.createCriteria();
            cr.andSupUserIdEqualTo(detail.getSource());
            cr.andSubUserIdEqualTo(userId);
            try {
                List<UserAgent> list = readUserAgentDao.selectByExample(ex);
                if (list != null && list.size() > 0) {
                    UserAgent agent = list.get(0);
                    if (agent.getStatus() >1 ) {
                        agent.setStatus(1);
                        writeUserAgentDao.updateByPrimaryKeySelective(agent);
                    }
                } else {
                    UserAgent agent = new UserAgent();
                    agent.setCreateTime(DateUtil.getTimeStr(new Date()));
                    agent.setDot(1);
                    if(isReview && detail.getIsReview() > 0){
                        agent.setStatus(0);//申请
                    }else {
                        agent.setStatus(1);
                    }
                    agent.setSupUserId(detail.getUserId());//原产品创建人
                    agent.setSubUserId(userId);
                    agent.setSupProductId(detail.getProductId());//原产品
                    agent.setSubProductId(userProduct.getProductId());
                    //代理的产品
                    ret = writeUserAgentDao.insertSelective(agent);

                }
            } catch (DaoException e) {
                e.printStackTrace();
            }
            if (ret > 0) { //推送
                ret = userProduct.getProductId();
                try {
                    if (!StringUtil.containEmpty(platform)) {
                        Map<String, Object> insertParam = new HashMap<String, Object>();
                        insertParam.put("userId", detail.getSource());
                        //  insertParam.put("userId", subUserId);
                        insertParam.put("platform", platform);
                        insertParam.put("type", 1);//申请代理
                        AsyncThread runable = new AsyncThread(insertParam);
                        runable.run();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        if (ret > 0 && isReview && detail.getIsReview() > 0) { //原产品代理需要审核
            AgentReview review = new AgentReview();
            review.setApplyPid(userProduct.getProductId());
            review.setProductId(productId);
            review.setApplyUid(userId);
            review.setHandUid(detail.getSource());
            review.setTemplate(template);
            review.setUrls(urls);
            review.setStatus(0);
            try {
                review.setCreateTime(com.smartlbs.util.DateUtil.getNowDateTimeString());
                int i = agentReviewService.add(review);
                if(i > 0){
                    map.put("reviewId",review.getReviewId());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        map.put("ret",ret);
        return map;
    }
    @Transactional
    @Override
    public int cancelAgent(int uid, int userId, int agentId) throws ServiceException {
        int ret = 0;
        try {
            //如果代理人有相关未处理申请,则不能取消
            int i1 = userApplyService.querCount(uid, 0, userId, 0, 0, false, false, true, 0, 0);
            if (i1 > 0) {
                return -998;
            }
            Map map = new HashMap();
            map.put("status", 2);
            map.put("updateTime", DateUtil.getTimeStr(new Date()));
            if (agentId > 0) {
                map.put("agentId", agentId);
            }
            if (uid > 0) {
                map.put("supUserId", uid);
            }
            if (userId > 0) {
                map.put("subUserId", userId);
            }
            ret = writeUserAgentDao.cancelAgent(map);
            if (ret > 0) {
                UserAgent agent1 = readUserAgentDao.selectByPrimaryKey(agentId);
                Map param = new HashMap();
                param.put("source", agent1.getSupUserId());
                param.put("agentStatus", 3);//取消代理
                param.put("productType", 2);
                param.put("status", 1);
                param.put("userId", agent1.getSubUserId());
                param.put("updateTime", com.smartlbs.util.DateUtil.getNowDateTimeString());

                int i = writeUserProductDao.updateAgent(param);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
    @Transactional
    @Override
    public PageDto query(int pageNum, int rows, int supUserId, int supProductId, int status) throws ServiceException {
        PageDto pageDto = new PageDto();
        PageHelper.startPage(pageNum, rows);
        Map map = new HashMap();
        map.put("supUserId", supUserId);
        try {
            List<Map> agents = readUserAgentDao.qryAgentRecord(map);
            if (agents != null && agents.size() > 0) {
                PageInfo info = new PageInfo(agents);
                List<Map> dtos = new ArrayList();
                for (Map agent : agents) {
                    Map p1 = new HashMap();
                    p1.put("userId", agent.get("subUserId"));
                    Map user = rAppLoginDao.qryUserInfoByUserId(p1);
                    agent.putAll(user);
                    dtos.add(agent);
                }
                pageDto.setList(dtos);
                pageDto.setInfo(info);
            }
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return pageDto;
    }

    @Override
    public int queryCount(int supUserId, int subUserId, int supProudctId, int status) throws ServiceException {
        int count = 0;
        Map map = new HashMap();
        if (supUserId > 0) {
            map.put("supUserId", supUserId);
        }
        if (subUserId > 0) {
            map.put("subUserId", subUserId);
        }
        try {
            count = readUserAgentDao.qryAgentRecordCount(map);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return count;
    }

    private void setExt(UserAgentDTO dto) throws Exception {

    }


    /**
     * 消息推送
     */
    private void pushMessage(Map<String, Object> param) throws ServiceException {
        Map<String, Object> pushInfo = null;
        Map<String, String> map_jp = Maps.newHashMap();
        try {
            pushInfo = loginLogDao.qryPushIdByUserId(param);
            if (pushInfo == null || pushInfo.isEmpty() || pushInfo.get("pushId") == null || "".equals(pushInfo.get("pushId"))) {
                return;
            }
            String pushTitle = "";
            String pushContent = "";
            int type = StringUtil.getInt(param.get("type"), 0);
            if (type == 1) { //1产品申请
                pushTitle = "【微介】产品代理提醒";
                pushContent = "您有代理，请注意查收";
            }

            // 推送
            if ("Android".equals(param.get("platform")) || "wexin".equals(param.get("platform"))) {
                // jpush
                String deviceAndro = pushInfo.get("pushId") == null ? "" : pushInfo.get("pushId").toString();
                //push消息
//                JPushUtils.pushAndroidMessageByRegistrationID(pushTitle, pushContent, deviceAndro);
                JPushUtils.pushAndroidNotificationByRegistrationID(pushTitle, pushContent, new HashMap(), deviceAndro);
            } else {
                if (param.get("IOS") != null) {
                    String[] deviceIos = param.get("IOS").toString().split(",");
                    JPushUtils.pushIosNotificationByRegistrationID(pushContent, map_jp, deviceIos);
                }
            }
            logger.info("消息推送成功");
        } catch (DaoException e) {
            logger.info("消息推送失败");
            throw new ServiceException(e.getCause());
        }
    }

    public class AsyncThread implements Runnable {
        private Map<String, Object> param;

        AsyncThread(Map<String, Object> param) {
            this.param = param;
        }

        @Override
        public void run() {
            try {
                pushMessage(param);
            } catch (ServiceException e) {
                e.printStackTrace();
            }
        }
    }
    @Transactional
    @Override
    public int reviewAgent(int subUid, int supUid ,  int status) throws ServiceException {
        int ret = 0;
        Map map = new HashMap();
        map.put("subUid",subUid);
        map.put("supUId",supUid);
        map.put("status",status);
        try {
            ret = writeUserAgentDao.agentReview(map);
        } catch (DaoException e) {
            e.printStackTrace();
        }
        return ret;
    }
}
